<!DOCTYPE html><html lang="zh-CN" data-theme="dark"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>swift-WCDB移动数据库使用 | Albert Yuan's Blog</title><meta name="keywords" content="Swift"><meta name="author" content="Albert Yuan"><meta name="copyright" content="Albert Yuan"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#0d0d0d"><meta name="referrer" content="no-referrer"><meta name="description" content="1、WCDB.Swfit 简介 WCDB 的最基础的调用过程大致分为三个步骤   1、模型绑定 —- 基于数据模型  2、创建数据库与表 —- 基于WCDB封装 ：创库建表、增删改查方法  3、操作数据 —- 基于业务逻辑    1.1 基本使用流程了解1.1.1模型绑定 WCDB 基于 Swift 4.0 的 Codable 协议实现模型绑定的过程。  对于已经存在的 Sample 类：(现有的">
<meta property="og:type" content="article">
<meta property="og:title" content="swift-WCDB移动数据库使用">
<meta property="og:url" content="https://yllove.gitee.io/2022/06/08/Swift/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/index.html">
<meta property="og:site_name" content="Albert Yuan&#39;s Blog">
<meta property="og:description" content="1、WCDB.Swfit 简介 WCDB 的最基础的调用过程大致分为三个步骤   1、模型绑定 —- 基于数据模型  2、创建数据库与表 —- 基于WCDB封装 ：创库建表、增删改查方法  3、操作数据 —- 基于业务逻辑    1.1 基本使用流程了解1.1.1模型绑定 WCDB 基于 Swift 4.0 的 Codable 协议实现模型绑定的过程。  对于已经存在的 Sample 类：(现有的">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.codexy.cn%2Fwp-content%2Fuploads%2F2018%2F03%2F1505728613416664.jpg&refer=http%3A%2F%2Fwww.codexy.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657266676&t=58ef0d1905112ebd13dd6914b5f4f996">
<meta property="article:published_time" content="2022-06-08T07:50:21.096Z">
<meta property="article:modified_time" content="2022-06-08T10:03:17.029Z">
<meta property="article:author" content="Albert Yuan">
<meta property="article:tag" content="Swift">
<meta property="article:tag" content="移动数据库">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.codexy.cn%2Fwp-content%2Fuploads%2F2018%2F03%2F1505728613416664.jpg&refer=http%3A%2F%2Fwww.codexy.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1657266676&t=58ef0d1905112ebd13dd6914b5f4f996"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://yllove.gitee.io/2022/06/08/Swift/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/instantsearch.js@2.10.5/dist/instantsearch.min.js" defer></script><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: {"appId":"X8NS0XSX99","apiKey":"b9d4530647c8b5bf7928a04c47752ad7","indexName":"albertyuan","hits":{"per_page":6},"languages":{"input_placeholder":"搜索文章","hits_empty":"找不到您查询的内容：${query}","hits_stats":"找到 ${hits} 条结果，用时 ${time} 毫秒"}},
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    jQuery: 'https://fastly.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://fastly.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://fastly.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: true,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'swift-WCDB移动数据库使用',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2022-06-08 18:03:17'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.2.0"><link rel="alternate" href="/blog/atom.xml" title="Albert Yuan's Blog" type="application/atom+xml">
</head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.codexy.cn%2Fwp-content%2Fuploads%2F2018%2F03%2F1505728613416664.jpg&amp;refer=http%3A%2F%2Fwww.codexy.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1657266676&amp;t=58ef0d1905112ebd13dd6914b5f4f996')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Albert Yuan's Blog</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">swift-WCDB移动数据库使用</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-06-08T07:50:21.096Z" title="发表于 2022-06-08 15:50:21">2022-06-08</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-06-08T10:03:17.029Z" title="更新于 2022-06-08 18:03:17">2022-06-08</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/Swift/">Swift</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>9分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="swift-WCDB移动数据库使用"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h3 id="1、WCDB-Swfit-简介"><a href="#1、WCDB-Swfit-简介" class="headerlink" title="1、WCDB.Swfit 简介"></a>1、WCDB.Swfit 简介</h3><ul>
<li><p><code>WCDB</code> 的最基础的调用过程大致分为三个步骤</p>
<blockquote>
<p> 1、模型绑定 —- 基于数据模型</p>
<p> 2、创建数据库与表 —- 基于WCDB封装 ：创库建表、增删改查方法</p>
<p> 3、操作数据 —- 基于业务逻辑</p>
</blockquote>
</li>
</ul>
<h4 id="1-1-基本使用流程了解"><a href="#1-1-基本使用流程了解" class="headerlink" title="1.1 基本使用流程了解"></a>1.1 基本使用流程了解</h4><h5 id="1-1-1模型绑定"><a href="#1-1-1模型绑定" class="headerlink" title="1.1.1模型绑定"></a>1.1.1模型绑定</h5><ul>
<li><p><code>WCDB</code> 基于 <code>Swift 4.0</code> 的 <code>Codable</code> 协议实现模型绑定的过程。</p>
</li>
<li><p>对于已经存在的 Sample 类：(现有的数据模型)</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Sample</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> identifier: <span class="type">Int</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> description: <span class="type">String</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>可通过以下代码将 <code>Sample</code> 类的 <code>identifier</code> 和 <code>description</code> 两个变量绑定到了表中同名字段：</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Sample</span>: <span class="title class_">TableCodable</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> identifier: <span class="type">Int</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> description: <span class="type">String</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">enum</span> <span class="title class_">CodingKeys</span>: <span class="title class_">String</span>, <span class="title class_">CodingTableKey</span> &#123;</span><br><span class="line">        <span class="keyword">typealias</span> <span class="type">Root</span> <span class="operator">=</span> <span class="type">Sample</span></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">let</span> objectRelationalMapping <span class="operator">=</span> <span class="type">TableBinding</span>(<span class="type">CodingKeys</span>.<span class="keyword">self</span>)</span><br><span class="line">        <span class="keyword">case</span> identifier</span><br><span class="line">        <span class="keyword">case</span> description</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//这部分代码基本都是固定模版</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure></li>
</ul>
<hr>
<h5 id="1-1-2-创库建表"><a href="#1-1-2-创库建表" class="headerlink" title="1.1.2 创库建表"></a>1.1.2 创库建表</h5><ul>
<li><p><code>One line of code</code> 是 <code>WCDB</code> 接口设计的一个基本原则，绝大部分的便捷接口都可以通过一行代码完成。</p>
</li>
<li><p>创建数据库对象: WCDB 会在创建数据库文件的同时，创建路径中所有未创建文件夹</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> database <span class="operator">=</span> <span class="type">Database</span>(withPath: <span class="string">&quot;~/Intermediate/Directories/Will/Be/Created/sample.db&quot;</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>创建数据库表:对于已进行模型绑定的类，同样只需一行代码完成。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 以下代码等效于 SQL：CREATE TABLE IF NOT EXISTS sampleTable(identifier INTEGER, description TEXT)</span></span><br><span class="line"><span class="keyword">try</span> database.create(table: <span class="string">&quot;sampleTable&quot;</span>, of: <span class="type">Sample</span>.<span class="keyword">self</span>)</span><br></pre></td></tr></table></figure>

<hr>
</li>
</ul>
<h5 id="1-1-3-增删改查操作"><a href="#1-1-3-增删改查操作" class="headerlink" title="1.1.3 增删改查操作"></a>1.1.3 增删改查操作</h5><ul>
<li>基本的增删查改同样是 One line of code</li>
</ul>
<h6 id="1-1-3-1-插入操作"><a href="#1-1-3-1-插入操作" class="headerlink" title="1.1.3.1 插入操作"></a>1.1.3.1 插入操作</h6><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">//Prepare data</span></span><br><span class="line"><span class="keyword">let</span> object <span class="operator">=</span> <span class="type">Sample</span>()</span><br><span class="line">object.identifier <span class="operator">=</span> <span class="number">1</span></span><br><span class="line">object.description <span class="operator">=</span> <span class="string">&quot;sample_insert&quot;</span></span><br><span class="line"><span class="comment">//Insert</span></span><br><span class="line"><span class="keyword">try</span> database.insert(objects: object, intoTable: <span class="string">&quot;sampleTable&quot;</span>)</span><br></pre></td></tr></table></figure>

<h6 id="1-1-3-2-查找操作"><a href="#1-1-3-2-查找操作" class="headerlink" title="1.1.3.2 查找操作"></a>1.1.3.2 查找操作</h6><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> objects: [<span class="type">Sample</span>] <span class="operator">=</span> <span class="keyword">try</span> database.getObjects(fromTable: <span class="string">&quot;sampleTable&quot;</span>)</span><br></pre></td></tr></table></figure>

<h6 id="1-1-3-3-更新操作"><a href="#1-1-3-3-更新操作" class="headerlink" title="1.1.3.3 更新操作"></a>1.1.3.3 更新操作</h6><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//Prepare data</span></span><br><span class="line"><span class="keyword">let</span> object <span class="operator">=</span> <span class="type">Sample</span>()</span><br><span class="line">object.description <span class="operator">=</span> <span class="string">&quot;sample_update&quot;</span></span><br><span class="line"><span class="comment">//Update</span></span><br><span class="line"><span class="keyword">try</span> database.update(table: <span class="string">&quot;sampleTable&quot;</span>,</span><br><span class="line">                       on: <span class="type">Sample</span>.<span class="type">Properties</span>.description,</span><br><span class="line">                     with: object,</span><br><span class="line">                    where: <span class="type">Sample</span>.<span class="type">Properties</span>.identifier <span class="operator">&gt;</span> <span class="number">0</span>)</span><br><span class="line">                    <span class="comment">//类似 Sample.Properties.identifier &gt; 0 的语法是 WCDB 的特性，它能通过 Swift 语法来进行 SQL 操作</span></span><br></pre></td></tr></table></figure>

<h6 id="1-1-3-4-删除操作"><a href="#1-1-3-4-删除操作" class="headerlink" title="1.1.3.4 删除操作"></a>1.1.3.4 删除操作</h6><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> database.delete(fromTable: <span class="string">&quot;sampleTable&quot;</span>)</span><br></pre></td></tr></table></figure>

<hr>
<h4 id="1-2-使用流程中的细节处理"><a href="#1-2-使用流程中的细节处理" class="headerlink" title="1.2  使用流程中的细节处理"></a>1.2  使用流程中的细节处理</h4><h5 id="1-2-1-关于-Swift-模型绑定"><a href="#1-2-1-关于-Swift-模型绑定" class="headerlink" title="1.2.1 关于 Swift 模型绑定"></a>1.2.1 关于 Swift 模型绑定</h5><ul>
<li><p>模型绑定（Object-relational Mapping，简称 ORM），通过对 Swift 类或结构进行绑定，形成类或结构 - 表模型、类或结构对象 - 表的映射关系，从而达到通过对象直接操作数据库的目的。</p>
</li>
<li><p>WCDB Swift 的模型绑定分为五个部分：这其中大部分是格式化的模版代码，我们在最后介绍文件模版和代码提示模版，以简化模型绑定的操作。</p>
<blockquote>
<p>字段映射<br>字段约束<br>索引<br>表约束<br>虚拟表映射</p>
</blockquote>
</li>
</ul>
<h6 id="字段映射"><a href="#字段映射" class="headerlink" title="字段映射"></a>字段映射</h6><figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Sample</span>: <span class="title class_">TableCodable</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> identifier: <span class="type">Int</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> description: <span class="type">String</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> offset: <span class="type">Int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">    <span class="keyword">var</span> debugDescription: <span class="type">String</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">        </span><br><span class="line">  <span class="comment">//WCDB Swift 的字段映射基于 Swift 4.0 的 Codable 协议实现。以下是一个字段映射的示例代码：</span></span><br><span class="line">    <span class="keyword">enum</span> <span class="title class_">CodingKeys</span>: <span class="title class_">String</span>, <span class="title class_">CodingTableKey</span> &#123;</span><br><span class="line">      </span><br><span class="line">      <span class="comment">//固定格式</span></span><br><span class="line">      <span class="keyword">typealias</span> <span class="type">Root</span> <span class="operator">=</span> <span class="type">Sample</span></span><br><span class="line">      <span class="keyword">static</span> <span class="keyword">let</span> objectRelationalMapping <span class="operator">=</span> <span class="type">TableBinding</span>(<span class="type">CodingKeys</span>.<span class="keyword">self</span>)</span><br><span class="line">      </span><br><span class="line">      <span class="comment">//映射字段</span></span><br><span class="line">      <span class="keyword">case</span> identifier <span class="operator">=</span> <span class="string">&quot;id&quot;</span></span><br><span class="line">      <span class="keyword">case</span> description</span><br><span class="line">      <span class="keyword">case</span> offset <span class="operator">=</span> <span class="string">&quot;db_offset&quot;</span> <span class="comment">//offset是数据库中的关键字，需要处理</span></span><br><span class="line">      </span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//与 Swift 的 Codable 协议不同的是，即便是所有字段都需要绑定，这里也必须列举每一个需要绑定的字段。因为 CodingKeys 除了用于模型绑定，还将用于语言集成查询，我们会在后面章节中介绍</span></span><br></pre></td></tr></table></figure>

<blockquote>
<ul>
<li>在类内定义 CodingKeys 的枚举类，并遵循 <code>String</code> 和 <code>CodingTableKey</code>。</li>
<li>枚举列举每一个需要定义的字段。</li>
<li>对于变量名与表的字段名不一样的情况，可以使用别名进行映射，如 case identifier &#x3D; “id”</li>
<li>对于不需要写入数据库的字段，则不需要在 CodingKeys 内定义，如 debugDescription</li>
<li>对于变量名与 SQLite 的保留关键字冲突的字段，同样可以使用别名进行映射，如 offset 是 SQLite 的关键字。</li>
</ul>
</blockquote>
<ul>
<li><p>字段映射定义完成后，调用 <code>create(table:of:)</code> 接口即可根据这个定义创建表</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 以下代码等效于 SQL：CREATE TABLE IF NOT EXISTS sampleTable(id INTEGER, description TEXT, db_offset INTEGER)</span></span><br><span class="line"><span class="keyword">try</span> database.create(table: <span class="string">&quot;sampleTable&quot;</span>, of: <span class="type">Sample</span>.<span class="keyword">self</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>并非所有类型的变量都支持被绑定为字段。WCDB Swift 内建了常用类型的支持，包括：</p>
<table>
<thead>
<tr>
<th>数据库中的类型</th>
<th>类型</th>
</tr>
</thead>
<tbody><tr>
<td>32 位整型</td>
<td>Bool, Int, Int8, Int16, Int32, UInt, UInt8, UInt16, UInt32</td>
</tr>
<tr>
<td>64 位整型</td>
<td>Int64, UInt64, Date</td>
</tr>
<tr>
<td>浮点型</td>
<td>Float, Double</td>
</tr>
<tr>
<td>字符串类型</td>
<td>String, URL</td>
</tr>
<tr>
<td>二进制类型</td>
<td>Data, Array, Dictionary, Set</td>
</tr>
</tbody></table>
<blockquote>
<p>其中 Date 以时间戳的形式存储, Array、Dictionary、Set 以 JSON 的形式存储。</p>
<p>对于没有内建支持的类型，开发者可以手动为其添加支持。我们将在<code>自定义字段映射类型</code>一章进一步介绍</p>
</blockquote>
</li>
</ul>
<hr>
<h6 id="字段约束"><a href="#字段约束" class="headerlink" title="字段约束"></a>字段约束</h6><ul>
<li><p>什么是字段约束：用于定于针对单个字段的约束，如主键约束、非空约束、唯一约束、默认值等</p>
</li>
<li><p>ColumnConstraintBinding字段约束是 <code>TableEncodable</code> 的一个可选函数，可根据需求选择实现或不实现。它用于定于针对单个字段的约束，如主键约束、非空约束、唯一约束、默认值等</p>
</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Sample</span>: <span class="title class_">TableCodable</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> identifier: <span class="type">Int</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> description: <span class="type">String</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">        </span><br><span class="line"> 		</span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">    <span class="keyword">enum</span> <span class="title class_">CodingKeys</span>: <span class="title class_">String</span>, <span class="title class_">CodingTableKey</span> &#123;</span><br><span class="line">        <span class="keyword">typealias</span> <span class="type">Root</span> <span class="operator">=</span> <span class="type">Sample</span></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">let</span> objectRelationalMapping <span class="operator">=</span> <span class="type">TableBinding</span>(<span class="type">CodingKeys</span>.<span class="keyword">self</span>)</span><br><span class="line">       </span><br><span class="line">      <span class="comment">//字段映射</span></span><br><span class="line">        <span class="keyword">case</span> identifier</span><br><span class="line">        <span class="keyword">case</span> description</span><br><span class="line"></span><br><span class="line">      <span class="comment">//字段约束：columnConstraintBindings(列约束绑定)</span></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">var</span> columnConstraintBindings: [<span class="type">CodingKeys</span>: <span class="type">ColumnConstraintBinding</span>]<span class="operator">?</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> [</span><br><span class="line">                <span class="comment">//是否为主键</span></span><br><span class="line">                identifier: <span class="type">ColumnConstraintBinding</span>(isPrimary: <span class="literal">true</span>), </span><br><span class="line">                <span class="comment">//非空与默认值</span></span><br><span class="line">                description: <span class="type">ColumnConstraintBinding</span>(isNotNull: <span class="literal">true</span>, defaultTo: <span class="string">&quot;defaultDescription&quot;</span>),</span><br><span class="line">            ]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">  </span><br><span class="line">  <span class="comment">//TableEncodable协议定义的属性</span></span><br><span class="line">	  <span class="keyword">var</span> isAutoIncrement: <span class="type">Bool</span> <span class="operator">=</span> <span class="literal">false</span> <span class="comment">// 用于定义是否使用自增的方式插入</span></span><br><span class="line">    <span class="keyword">var</span> lastInsertedRowID: <span class="type">Int64</span> <span class="operator">=</span> <span class="number">0</span> <span class="comment">// 用于获取自增插入后的主键值</span></span><br><span class="line">  </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">字段约束通过 CodingKeys 到字段约束的字典实现，定义每个 CodingKeys 对应的约束</span></span><br><span class="line"><span class="comment">ColumnConstraintBinding 初始化函数的声明如下：</span></span><br><span class="line"><span class="comment"></span></span><br><span class="line"><span class="comment">ColumnConstraintBinding(</span></span><br><span class="line"><span class="comment">    isPrimary: Bool = false, // 该字段是否为主键。字段约束中只能同时存在一个主键</span></span><br><span class="line"><span class="comment">    orderBy term: OrderTerm? = nil, // 当该字段是主键时，存储顺序是升序还是降序</span></span><br><span class="line"><span class="comment">    isAutoIncrement: Bool = false, // 当该字段是主键时，其是否支持自增。只有整型数据可以定义为自增。</span></span><br><span class="line"><span class="comment">    onConflict conflict: Conflict? = nil, // 当该字段是主键时，若产生冲突，应如何处理</span></span><br><span class="line"><span class="comment">    isNotNull: Bool = false, // 该字段是否可以为空</span></span><br><span class="line"><span class="comment">    isUnique: Bool = false, // 该字段是否可以具有唯一性</span></span><br><span class="line"><span class="comment">    defaultTo defaultValue: ColumnDef.DefaultType? = nil // 该字段在数据库内使用什么默认值</span></span><br><span class="line"><span class="comment">)</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<ul>
<li><p>以上约束按需进行定义或者不定义即可。 定义完成后，同样调用 create(table:of:) 接口即可根据这个定义创建表。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 以下代码等效于 SQL：CREATE TABLE IF NOT EXISTS sampleTable(identifier INTEGER PRIMARY KEY, description TEXT NOT NULL DEFAULT &#x27;defaultDescription&#x27;)</span></span><br><span class="line"><span class="keyword">try</span> database.create(table: <span class="string">&quot;sampleTable&quot;</span>, of: <span class="type">Sample</span>.<span class="keyword">self</span>)</span><br></pre></td></tr></table></figure>
</li>
<li><p>自增属性</p>
<blockquote>
<ul>
<li>定义了 <code>isPrimary</code>: 的字段，支持以自增的方式进行插入数据。但仍可以通过非自增的方式插入数据。</li>
<li>当需要进行自增插入时，对象需设置 <code>isAutoIncrement</code> 参数为 <code>true</code>，则数据库会使用 已有数据中最大的值+1 作为主键的值。</li>
</ul>
</blockquote>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> autoIncrementObject <span class="operator">=</span> <span class="type">Sample</span>()</span><br><span class="line">autoIncrementObject.isAutoIncrement <span class="operator">=</span> <span class="literal">true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 插入自增数据</span></span><br><span class="line"><span class="keyword">try</span> database.insert(objects: autoIncrementObject, intoTable: <span class="string">&quot;sampleTable&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(autoIncrementObject.lastInsertedRowID) <span class="comment">// 输出 1</span></span><br><span class="line"><span class="comment">//对于自增插入的数据，可以在类内定义 lastInsertedRowID 字段，并以此获取插入的值。</span></span><br><span class="line"><span class="comment">//若类只会使用自增的方式插入，而不需要指定值的方式插入，可以在定义时直接设置 isAutoIncrement 为 true。如：var isAutoIncrement: Bool &#123; return true &#125;⭐️⭐️⭐️</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 再次插入自增数据</span></span><br><span class="line"><span class="keyword">try</span> database.insert(objects: autoIncrementObject, intoTable: <span class="string">&quot;sampleTable&quot;</span>)</span><br><span class="line"><span class="built_in">print</span>(autoIncrementObject.lastInsertedRowID) <span class="comment">// 输出 2</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 插入非自增的指定数据</span></span><br><span class="line"><span class="keyword">let</span> specificObject <span class="operator">=</span> <span class="type">Sample</span>()</span><br><span class="line">specificObject.identifier <span class="operator">=</span> <span class="number">10</span></span><br><span class="line"><span class="keyword">try</span> database.insert(objects: specificObject, intoTable: <span class="string">&quot;sampleTable&quot;</span>)</span><br></pre></td></tr></table></figure>

<hr>
</li>
</ul>
<h6 id="索引"><a href="#索引" class="headerlink" title="索引"></a>索引</h6><ul>
<li>IndexBinding索引是 <code>TableEncodable</code> 的一个可选函数，可根据需求选择实现或不实现。</li>
<li>它用于定于针对单个或多个字段的索引，索引后的数据能有更高的查询效率。</li>
<li>以下是一个定义索引的示例代码：</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Sample</span>: <span class="title class_">TableCodable</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> identifier: <span class="type">Int</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> description: <span class="type">String</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> multiIndexPart1: <span class="type">Int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">    <span class="keyword">var</span> multiIndexPart2: <span class="type">Int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">    <span class="keyword">enum</span> <span class="title class_">CodingKeys</span>: <span class="title class_">String</span>, <span class="title class_">CodingTableKey</span> &#123;</span><br><span class="line">        <span class="keyword">typealias</span> <span class="type">Root</span> <span class="operator">=</span> <span class="type">Sample</span></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">let</span> objectRelationalMapping <span class="operator">=</span> <span class="type">TableBinding</span>(<span class="type">CodingKeys</span>.<span class="keyword">self</span>)</span><br><span class="line">      </span><br><span class="line">        <span class="keyword">case</span> identifier</span><br><span class="line">        <span class="keyword">case</span> description</span><br><span class="line">        <span class="keyword">case</span> multiIndexPart1</span><br><span class="line">        <span class="keyword">case</span> multiIndexPart2</span><br><span class="line"></span><br><span class="line">      <span class="comment">//具体应用场景是什么？？？</span></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">var</span> indexBindings: [<span class="type">IndexBinding</span>.<span class="type">Subfix</span>: <span class="type">IndexBinding</span>]<span class="operator">?</span> &#123;</span><br><span class="line">            <span class="keyword">return</span> [</span><br><span class="line">                <span class="string">&quot;_uniqueIndex&quot;</span>: <span class="type">IndexBinding</span>(isUnique: <span class="literal">true</span>, indexesBy: identifier),</span><br><span class="line">                <span class="string">&quot;_descendingIndex&quot;</span>: <span class="type">IndexBinding</span>(indexesBy: description.asIndex(orderBy: .descending)),</span><br><span class="line">                <span class="string">&quot;_multiIndex&quot;</span>: <span class="type">IndexBinding</span>(indexesBy: multiIndexPart1, multiIndexPart2.asIndex(orderBy: .ascending))</span><br><span class="line">            ]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ul>
<li><p>索引通过索引后缀与索引绑定的映射实现。</p>
<blockquote>
<ul>
<li>对于需要特别指明索引存储顺序的字段，可以通过 asIndex(orderBy:) 函数指定，如 description.asIndex(orderBy: .descending)。</li>
<li>对于具有唯一性的索引，可以通过 isUnique: 参数指定，如 IndexBinding(isUnique: true, indexesBy: identifier)。</li>
<li>对于由多个字段组成的联合索引，可以通过 indexesBy: 进行指定，如 (indexesBy: multiIndexPart1, multiIndexPart2.asIndex(orderBy: .ascending))</li>
</ul>
</blockquote>
<ul>
<li><p>索引定义完成后，同样调用 create(table:of:) 接口即可根据这个定义创建表。</p>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 以下代码等效于 SQL：</span></span><br><span class="line"><span class="comment">// CREATE TABLE IF NOT EXISTS sampleTable(identifier INTEGER, description TEXT, multiIndexPart1 INTEGER, multiIndexPart2 INTEGER)</span></span><br><span class="line"><span class="comment">// CREATE UNIQUE INDEX IF NOT EXISTS sampleTable_uniqueIndex on sampleTable(identifier)</span></span><br><span class="line"><span class="comment">// CREATE INDEX IF NOT EXISTS sampleTable_descendingIndex on sampleTable(description DESC)</span></span><br><span class="line"><span class="comment">// CREATE INDEX IF NOT EXISTS sampleTable_multiIndex on sampleTable(multiIndexPart1, multiIndexPart2 ASC)</span></span><br><span class="line"><span class="keyword">try</span> database.create(table: <span class="string">&quot;sampleTable&quot;</span>, of: <span class="type">Sample</span>.<span class="keyword">self</span>)</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
<hr>
<h6 id="表约束"><a href="#表约束" class="headerlink" title="表约束"></a>表约束</h6><ul>
<li>MultiPrimaryBinding表约束是 <code>TableEncodable</code> 的一个可选函数，可根据需求选择实现或不实现。</li>
<li>它用于定于针对多个字段或表本身的约束。</li>
<li>以下是一个表约束的示例代码：</li>
</ul>
<figure class="highlight swift"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">class</span> <span class="title class_">Sample</span>: <span class="title class_">TableCodable</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> identifier: <span class="type">Int</span>? <span class="operator">=</span> <span class="literal">nil</span></span><br><span class="line">    <span class="keyword">var</span> multiPrimaryKeyPart1: <span class="type">Int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">    <span class="keyword">var</span> multiPrimaryKeyPart2: <span class="type">Int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">    <span class="keyword">var</span> multiUniquePart1: <span class="type">Int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">    <span class="keyword">var</span> multiUniquePart2: <span class="type">Int</span> <span class="operator">=</span> <span class="number">0</span></span><br><span class="line">        </span><br><span class="line">    <span class="keyword">enum</span> <span class="title class_">CodingKeys</span>: <span class="title class_">String</span>, <span class="title class_">CodingTableKey</span> &#123;</span><br><span class="line">        <span class="keyword">typealias</span> <span class="type">Root</span> <span class="operator">=</span> <span class="type">Sample</span></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">let</span> objectRelationalMapping <span class="operator">=</span> <span class="type">TableBinding</span>(<span class="type">CodingKeys</span>.<span class="keyword">self</span>)</span><br><span class="line">        <span class="keyword">case</span> identifier</span><br><span class="line">        <span class="keyword">case</span> multiPrimaryKeyPart1</span><br><span class="line">        <span class="keyword">case</span> multiPrimaryKeyPart2</span><br><span class="line">        <span class="keyword">case</span> multiUniquePart1</span><br><span class="line">        <span class="keyword">case</span> multiUniquePart2</span><br><span class="line"></span><br><span class="line">        <span class="keyword">static</span> <span class="keyword">var</span> tableConstraintBindings: [<span class="type">TableConstraintBinding</span>.<span class="type">Name</span>: <span class="type">TableConstraintBinding</span>]<span class="operator">?</span> &#123;</span><br><span class="line">            <span class="keyword">let</span> multiPrimaryBinding <span class="operator">=</span></span><br><span class="line">                <span class="type">MultiPrimaryBinding</span>(indexesBy: multiPrimaryKeyPart1.asIndex(orderBy: .descending), multiPrimaryKeyPart2)</span><br><span class="line">            <span class="keyword">let</span> multiUniqueBinding <span class="operator">=</span></span><br><span class="line">                <span class="type">MultiUniqueBinding</span>(indexesBy: multiUniquePart1, multiUniquePart2.asIndex(orderBy: .ascending))</span><br><span class="line">            <span class="keyword">return</span> [</span><br><span class="line">                <span class="string">&quot;MultiPrimaryConstraint&quot;</span>: multiPrimaryBinding,</span><br><span class="line">                <span class="string">&quot;MultiUniqueConstraint&quot;</span>: multiUniqueBinding</span><br><span class="line">            ]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<hr>
<h6 id="虚拟表映射"><a href="#虚拟表映射" class="headerlink" title="虚拟表映射"></a>虚拟表映射</h6><hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">Albert Yuan</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yllove.gitee.io/2022/06/08/Swift/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/">https://yllove.gitee.io/2022/06/08/Swift/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/swift-WCDB%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93%E4%BD%BF%E7%94%A8/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yllove.gitee.io" target="_blank">Albert Yuan's Blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/Swift/">Swift</a><a class="post-meta__tags" href="/blog/tags/%E7%A7%BB%E5%8A%A8%E6%95%B0%E6%8D%AE%E5%BA%93/">移动数据库</a></div><div class="post_share"><div class="social-share" data-image="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.codexy.cn%2Fwp-content%2Fuploads%2F2018%2F03%2F1505728613416664.jpg&amp;refer=http%3A%2F%2Fwww.codexy.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1657266676&amp;t=58ef0d1905112ebd13dd6914b5f4f996" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://fastly.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2022/05/24/iOS%E9%9F%B3%E8%A7%86%E9%A2%91%E5%BC%80%E5%8F%91/ios-AVFoundataion%E6%A1%86%E6%9E%B6/ios-AVFoundataion%E6%A1%86%E6%9E%B6/"><img class="prev-cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimages2017.cnblogs.com%2Fblog%2F739006%2F201801%2F739006-20180109111943957-1007678712.png&amp;refer=http%3A%2F%2Fimages2017.cnblogs.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1657283398&amp;t=a85dac3688b647e5e1baa517633db000" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">ios-AVFoundataion框架</div></div></a></div><div class="next-post pull-right"><a href="/blog/2022/06/09/MacOS/mac%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%B8%B8%E7%94%A8%E5%BF%AB%E6%8D%B7%E9%94%AE/mac%E5%91%BD%E4%BB%A4%E8%A1%8C%E5%B8%B8%E7%94%A8%E5%BF%AB%E6%8D%B7%E9%94%AE/"><img class="next-cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.jy0662.com%2Fuploads%2Fallimg%2F170209%2F162350AZ-2.png&amp;refer=http%3A%2F%2Fwww.jy0662.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1657349373&amp;t=3e3591526d838cc6a23d24a101da87de" onerror="onerror=null;src='/blog/img/defaultCover.gif'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">mac命令行常用快捷键</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span> 相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2021/08/17/RxSwift/RxSwift初识/" title="RxSwift初识"><img class="cover" src= "" data-lazy-src="https://miro.medium.com/max/1400/1*WvSoiQrJV0Bjpau2_s9fmw.jpeg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-08-17</div><div class="title">RxSwift初识</div></div></a></div><div><a href="/blog/2021/09/15/RxSwift/RxSwift的使用详解1/" title="RxSwift的使用详解1"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018010609150332714.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-15</div><div class="title">RxSwift的使用详解1</div></div></a></div><div><a href="/blog/2021/09/17/RxSwift/RxSwift的使用详解10-条件和布尔操作符/" title="RxSwift的使用详解10-条件和布尔操作符"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018012419380031551.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-17</div><div class="title">RxSwift的使用详解10-条件和布尔操作符</div></div></a></div><div><a href="/blog/2021/09/16/RxSwift/RxSwift的使用详解2-响应式编程与传统编程的比较/" title="RxSwift的使用详解2-响应式编程与传统编程的比较"><img class="cover" src= "" data-lazy-src="https://www.hangge.com/blog_uploads/201801/2018010520271321260.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-16</div><div class="title">RxSwift的使用详解2-响应式编程与传统编程的比较</div></div></a></div><div><a href="/blog/2021/09/16/RxSwift/RxSwift的使用详解3-Observable介绍与创建可观察序列/" title="RxSwift的使用详解3-Observable介绍与创建可观察序列"><img class="cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.51yuansu.com%2Fpic3%2Fcover%2F00%2F90%2F36%2F58dbe747391e4_610.jpg&refer=http%3A%2F%2Fpic.51yuansu.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634356138&t=248a78e6bca1ed2479d732ae8ef28254" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-16</div><div class="title">RxSwift的使用详解3-Observable介绍与创建可观察序列</div></div></a></div><div><a href="/blog/2021/09/16/RxSwift/RxSwift的使用详解4-Observable订阅-事件监听-订阅销毁/" title="RxSwift的使用详解4-Observable订阅-事件监听-订阅销毁"><img class="cover" src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fnimg.ws.126.net%2F%3Furl%3Dhttp%253A%252F%252Fdingyue.ws.126.net%252F2021%252F0822%252Fc74e238ej00qy8783002cc000m800ekc.jpg%26thumbnail%3D650x2147483647%26quality%3D80%26type%3Djpg&refer=http%3A%2F%2Fnimg.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634363191&t=72ca99f133fe4756f19a0c538c073a3e" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-09-16</div><div class="title">RxSwift的使用详解4-Observable订阅-事件监听-订阅销毁</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="/blog/img/favicon.png" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">Albert Yuan</div><div class="author-info__description">博学之,审问之,慎思之,明辨之,笃行之</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">155</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">56</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">32</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/yuanliangYL"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/yuanliangYL" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="mailto:yuanliangios@163.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="qq:1023817403" target="_blank" title="QQ"><i class="fab fa-qq"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">love cat , love life</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81WCDB-Swfit-%E7%AE%80%E4%BB%8B"><span class="toc-text">1、WCDB.Swfit 简介</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-1-%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8%E6%B5%81%E7%A8%8B%E4%BA%86%E8%A7%A3"><span class="toc-text">1.1 基本使用流程了解</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-1-1%E6%A8%A1%E5%9E%8B%E7%BB%91%E5%AE%9A"><span class="toc-text">1.1.1模型绑定</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#1-1-2-%E5%88%9B%E5%BA%93%E5%BB%BA%E8%A1%A8"><span class="toc-text">1.1.2 创库建表</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#1-1-3-%E5%A2%9E%E5%88%A0%E6%94%B9%E6%9F%A5%E6%93%8D%E4%BD%9C"><span class="toc-text">1.1.3 增删改查操作</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#1-1-3-1-%E6%8F%92%E5%85%A5%E6%93%8D%E4%BD%9C"><span class="toc-text">1.1.3.1 插入操作</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#1-1-3-2-%E6%9F%A5%E6%89%BE%E6%93%8D%E4%BD%9C"><span class="toc-text">1.1.3.2 查找操作</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#1-1-3-3-%E6%9B%B4%E6%96%B0%E6%93%8D%E4%BD%9C"><span class="toc-text">1.1.3.3 更新操作</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#1-1-3-4-%E5%88%A0%E9%99%A4%E6%93%8D%E4%BD%9C"><span class="toc-text">1.1.3.4 删除操作</span></a></li></ol></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#1-2-%E4%BD%BF%E7%94%A8%E6%B5%81%E7%A8%8B%E4%B8%AD%E7%9A%84%E7%BB%86%E8%8A%82%E5%A4%84%E7%90%86"><span class="toc-text">1.2  使用流程中的细节处理</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-2-1-%E5%85%B3%E4%BA%8E-Swift-%E6%A8%A1%E5%9E%8B%E7%BB%91%E5%AE%9A"><span class="toc-text">1.2.1 关于 Swift 模型绑定</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#%E5%AD%97%E6%AE%B5%E6%98%A0%E5%B0%84"><span class="toc-text">字段映射</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E5%AD%97%E6%AE%B5%E7%BA%A6%E6%9D%9F"><span class="toc-text">字段约束</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E7%B4%A2%E5%BC%95"><span class="toc-text">索引</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E8%A1%A8%E7%BA%A6%E6%9D%9F"><span class="toc-text">表约束</span></a></li><li class="toc-item toc-level-6"><a class="toc-link" href="#%E8%99%9A%E6%8B%9F%E8%A1%A8%E6%98%A0%E5%B0%84"><span class="toc-text">虚拟表映射</span></a></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包"><img src= "" data-lazy-src="https://img.mp.itc.cn/upload/20170409/1a8f793d7282451cbd1beb6841608c90_th.jpeg" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 自定义网页下载IPA包"/></a><div class="content"><a class="title" href="/blog/2023/02/07/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS-%E8%87%AA%E5%AE%9A%E4%B9%89%E7%BD%91%E9%A1%B5%E4%B8%8B%E8%BD%BDIPA%E5%8C%85/" title="iOS 自定义网页下载IPA包">iOS 自定义网页下载IPA包</a><time datetime="2023-02-07T02:46:29.851Z" title="更新于 2023-02-07 10:46:29">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS"><img src= "" data-lazy-src="https://pic4.zhimg.com/v2-6a115fea4db1ad770dccf4119bfab36f_1440w.jpg?source=172ae18b" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="flutter接入原生-iOS"/></a><div class="content"><a class="title" href="/blog/2023/02/06/Flutter/Flutter%E6%8E%A5%E5%85%A5%E5%8E%9F%E7%94%9F-iOS/" title="flutter接入原生-iOS">flutter接入原生-iOS</a><time datetime="2023-02-07T01:18:53.661Z" title="更新于 2023-02-07 09:18:53">2023-02-07</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP"><img src= "" data-lazy-src="https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.winwin7.com%2Fuploadfile%2F2021%2F0114%2F20210114141748239.jpg&amp;refer=http%3A%2F%2Fwww.winwin7.com&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1673854539&amp;t=aad2108ffb799b04e94a28cc58f038f1" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="iOS 如何在模拟器中安装APP"/></a><div class="content"><a class="title" href="/blog/2022/12/17/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/iOS%20%E5%A6%82%E4%BD%95%E5%9C%A8%E6%A8%A1%E6%8B%9F%E5%99%A8%E4%B8%AD%E5%AE%89%E8%A3%85APP/" title="iOS 如何在模拟器中安装APP">iOS 如何在模拟器中安装APP</a><time datetime="2022-12-17T07:48:56.594Z" title="更新于 2022-12-17 15:48:56">2022-12-17</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库"><img src= "" data-lazy-src="https://photos.infinum.com/store/b558bd40787ecad225d9c66322f14522" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="swift常用三方库"/></a><div class="content"><a class="title" href="/blog/2021/08/05/Swift/swift%E5%B8%B8%E7%94%A8%E4%B8%89%E6%96%B9%E5%BA%93/" title="swift常用三方库">swift常用三方库</a><time datetime="2022-12-16T06:37:20.115Z" title="更新于 2022-12-16 14:37:20">2022-12-16</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup"><img src= "" data-lazy-src="/blog/img/defaultCover.png" onerror="this.onerror=null;this.src='/blog/img/defaultCover.gif'" alt="GCD进阶之DispatchWorkItem和DispatchGroup"/></a><div class="content"><a class="title" href="/blog/2022/12/12/iOS%E5%BC%80%E5%8F%91%E8%BF%9B%E9%98%B6/GCD%E8%BF%9B%E9%98%B6%E4%B9%8BDispatchWorkItem%E5%92%8CDispatchGroup/" title="GCD进阶之DispatchWorkItem和DispatchGroup">GCD进阶之DispatchWorkItem和DispatchGroup</a><time datetime="2022-12-12T07:19:37.277Z" title="更新于 2022-12-12 15:19:37">2022-12-12</time></div></div></div></div></div></div></main><footer id="footer" style="background-image: url('https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fwww.codexy.cn%2Fwp-content%2Fuploads%2F2018%2F03%2F1505728613416664.jpg&amp;refer=http%3A%2F%2Fwww.codexy.cn&amp;app=2002&amp;size=f9999,10000&amp;q=a80&amp;n=0&amp;g=0n&amp;fmt=auto?sec=1657266676&amp;t=58ef0d1905112ebd13dd6914b5f4f996')"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By Albert Yuan</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div><div class="footer_custom_text">Hi, welcom to my  blog</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="algolia-search"><div class="search-dialog"><div class="search-dialog__title" id="algolia-search-title">Algolia</div><div id="algolia-input-panel"><div id="algolia-search-input"></div></div><hr/><div id="algolia-search-results"><div id="algolia-hits"></div><div id="algolia-pagination"></div><div id="algolia-stats"></div></div><span class="search-close-button"><i class="fas fa-times"></i></span></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://fastly.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="/blog/js/search/algolia.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"><script>if (!window.MathJax) {
  window.MathJax = {
    tex: {
      inlineMath: [ ['$','$'], ["\\(","\\)"]],
      tags: 'ams'
    },
    chtml: {
      scale: 1.2
    },
    options: {
      renderActions: {
        findScript: [10, doc => {
          for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
            const display = !!node.type.match(/; *mode=display/)
            const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display)
            const text = document.createTextNode('')
            node.parentNode.replaceChild(text, node)
            math.start = {node: text, delim: '', n: 0}
            math.end = {node: text, delim: '', n: 0}
            doc.math.push(math)
          }
        }, ''],
        insertScript: [200, () => {
          document.querySelectorAll('mjx-container:not\([display]\)').forEach(node => {
            const target = node.parentNode
            if (target.nodeName.toLowerCase() === 'li') {
              target.parentNode.classList.add('has-jax')
            } else {
              target.classList.add('has-jax')
            }
          });
        }, '', false]
      }
    }
  }
  
  const script = document.createElement('script')
  script.src = 'https://fastly.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js'
  script.id = 'MathJax-script'
  script.async = true
  document.head.appendChild(script)
} else {
  MathJax.startup.document.state(0)
  MathJax.texReset()
  MathJax.typeset()
}</script><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'REc8eytE1gJDl3d8FkudLNlL-gzGzoHsz',
      appKey: 'gGO3y8I9oVlc4Cd5N1fizNPW',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://fastly.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !true) {
  if (true) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script id="canvas_nest" defer="defer" color="255,0,0" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-nest.min.js"></script><script src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://fastly.jsdelivr.net/npm/butterfly-extsrc@1/dist/click-heart.min.js" async="async" mobile="false"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>